﻿using log4net;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using PhysicalExamination5.Service;
using PhysicalExamination5.WebApi.Utility.JWT;

namespace PhysicalExamination5.WebApi.Controllers
{
    /// <summary>
    /// 文件相关
    /// </summary>
    [ApiController]
    [ApiVersion("1.0")]
    [Route("[controller]/v{version:apiVersion}")]
    public class FileController : Controller
    {
        //日志引入
        private static readonly ILog log = LogManager.GetLogger(typeof(FileController));
        private readonly IHttpContextAccessor _httpContextAccessor;
        //配置文件引入
        private readonly IConfiguration _configuration;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="db"></param>
        /// <param name="logger"></param>
        public FileController(IHttpContextAccessor httpContextAccessor, IConfiguration configuration)
        {
            _httpContextAccessor = httpContextAccessor;
            _configuration = configuration;

            //配置日志ip地址参数信息
            string ipAddress = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();
            log4net.GlobalContext.Properties["localIpAddress"] = ipAddress;
        }
        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="file">文件</param>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        [Route("[action]")]
        public async Task<IActionResult> FileUpload(IFormFile file, string filePath)
        {
            try
            {

                #region 声明变量

                string WebApiPath = $@"{_configuration["WebApiPath"]}:{Request.HttpContext.Connection.LocalPort}";

                var formFile = file;
                var webPath = Directory.GetCurrentDirectory();
                var savePath = Path.Combine(webPath, $@"UploadFile/{filePath}");
                double fileSizeInKb = 0.00;
                string strWanZhengUrl = "";

                #endregion

                #region 验证

                if (string.IsNullOrEmpty(filePath))
                {
                    return BadRequest(new ApiResult<object>
                    {
                        Success = 1,
                        Message = "路径为空!",
                        Data = null
                    });
                }

                #endregion

                #region 判断是否上传了文件

                if (formFile == null)
                {
                    return BadRequest(new ApiResult<object>
                    {
                        Success = 1,
                        Message = "上传失败，未找到相关文件!",
                        Data = null
                    });
                }

                #endregion

                #region 校验文件

                //文件后缀
                var fileExtension = Path.GetExtension(formFile.FileName);//获取文件格式，拓展名

                //判断文件大小
                var fileSize = formFile.Length;

                //计算文件大小
                fileSizeInKb = ConvertBytesToKilobytes(fileSize);

                if (fileExtension.Contains("jpg") || fileExtension.Contains("png") || fileExtension.Contains("jpeg"))
                {
                    if (fileSize > 1024 * 1024 * 3)
                    {
                        return BadRequest(new ApiResult<object>
                        {
                            Success = 1,
                            Message = "图片文件类型要求大小不可超过2MB",
                            Data = null
                        });
                    }
                }
                else if (fileExtension.Contains("pdf"))
                {
                    if (fileSize > 1024 * 1024 * 10)
                    {
                        return BadRequest(new ApiResult<object>
                        {
                            Success = 1,
                            Message = "PDF文件类型要求大小不可超过10MB",
                            Data = ""
                        });
                    }
                }
                else if (fileExtension.Contains("xlsx") || fileExtension.Contains("xls"))
                {
                    if (fileSize > 1024 * 1024 * 6)
                    {
                        return BadRequest(new ApiResult<object>
                        {
                            Success = 1,
                            Message = "表格文件类型要求大小不可超过6MB",
                            Data = ""
                        });
                    }
                }
                else
                {
                    return BadRequest(new ApiResult<object>
                    {
                        Success = 1,
                        Message = "当前文件格式[" + fileExtension + "]不允许上传",
                        Data = ""
                    });
                }

                #endregion

                #region 判断相对路径文是否存在不存在创建路径

                if (!Directory.Exists(savePath))
                {
                    Directory.CreateDirectory(savePath);
                }

                #endregion

                #region 判断文件是否存在存在删除文件

                savePath = Path.Combine(savePath,formFile.FileName);

                if (System.IO.File.Exists(savePath))
                {
                    System.IO.File.Delete(savePath);
                }

                #endregion

                #region 保存文件

                await Task.Run(() =>
                {
                    using (var fs = System.IO.File.Create(savePath))
                    {
                        formFile.CopyTo(fs);
                        fs.Flush();
                    }
                });
                //文件完整路径
                strWanZhengUrl = $@"{WebApiPath}/UploadFile/{filePath}/{formFile.FileName}";

                #endregion

                #region 返回信息

                return Ok(new ApiResult<object>
                {
                    Success = 0,
                    Message = "上传成功",
                    Data = strWanZhengUrl
                });

                #endregion

            }
            catch (Exception ex)
            {
                return StatusCode(500, new ApiResult<object>
                {
                    Success = 1000,
                    Message = ex.ToString(),
                    Data = null
                });
            }
        }
        private double ConvertBytesToKilobytes(long bytes)
        {
            return Math.Round((double)bytes / 1024, 2);
        }
    }
}
